from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression, SGDRegressor, Ridge, RidgeCV
from sklearn.metrics import mean_squared_error
import joblib

import pandas as pd


def dump_load():
    """
    模型保存和加载
    """
    # 1.获取数据
    diabetes = load_diabetes()
    print(diabetes)
    # 2.数据基本处理
    # 2.1 分割数据
    x_train, x_test, y_train, y_test = train_test_split(diabetes.data, diabetes.target, test_size= 0.2)
    # 3.特征工程-标准化
    transfer = StandardScaler()
    train = transfer.fit_transform(x_train)# 标准化训练数据
    test = transfer.fit_transform(x_test) # 标准化测试数据
    
    # # 4.机器学习-岭回归
    # # 4.1模型训练
    # # estimator = Ridge(alpha= 1.0)
    # estimator = RidgeCV(alphas=(0.001, 0.01, 0.1, 1, 10, 1000))
    # # 4.2 模型保存
    # joblib.dump(estimator, "./model/test.pkl")

    # 4.3 模型加载
    estimator = joblib.load("./model/test.pkl")
    # 数据 标签
    estimator.fit(train, y_train)
    print("模型偏置",estimator.intercept_,"\n")
    print("模型系数",estimator.coef_,"\n")
    # 5.模型评估
    # 5.1尝试预测
    
    y_pre = estimator.predict(test)# 预测
    print("预测值", y_pre, "\n")
    # 5.2 均方误差
    ret = mean_squared_error(y_test, y_pre)
    print("均方误差", ret, "\n")

dump_load()